<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>用户中心</title>
    <link rel="stylesheet" href="style.css">
</head>
<body>
    <header>
        <h1>用户中心</h1>
        <nav>
            <a href="index.html">首页</a>
            <a href="product-list.html">商品列表</a>
            <a href="user.html">用户中心</a>
        </nav>
    </header>

    <main>
        <section class="user-info" id="user-info-section">
            <!-- 用户信息将通过JS动态加载 -->
        </section>

        <section class="auth-forms" id="login-section">
            <h2>登录</h2>
            <form id="login-form">
                <div>
                    <label for="login-username">用户名:</label>
                    <input type="text" id="login-username" required>
                </div>
                <div>
                    <label for="login-password">密码:</label>
                    <input type="password" id="login-password" required>
                </div>
                <button type="submit">登录</button>
            </form>
        </section>

        <section class="auth-forms" id="register-section">
            <h2>注册</h2>
            <form id="register-form">
                <div>
                    <label for="register-username">用户名:</label>
                    <input type="text" id="register-username" required>
                </div>
                <div>
                    <label for="register-password">密码:</label>
                    <input type="password" id="register-password" required>
                </div>
                <button type="submit">注册</button>
            </form>
        </section>

        <section class="order-history" id="order-history-section">
            <h2>订单历史</h2>
            <div id="order-list">
                <!-- 订单列表将通过JS动态加载 -->
            </div>
            <div class="pagination" id="order-pagination">
                <!-- 订单分页控件将通过JS动态加载 -->
            </div>
        </section>
    </main>

    <!-- 取消订单确认弹窗 -->
    <div id="cancel-modal" class="modal" style="display: none;">
        <div class="modal-content">
            <h3>确认取消订单</h3>
            <p>取消订单后，订单金额将退回您的账户余额。</p>
            <div class="modal-actions">
                <button id="confirm-cancel-btn" class="btn-primary">确认取消</button>
                <button id="cancel-cancel-btn" class="btn-secondary">返回</button>
            </div>
        </div>
    </div>

    <!-- 确认收货弹窗 -->
    <div id="confirm-modal" class="modal" style="display: none;">
        <div class="modal-content">
            <h3>确认收货</h3>
            <p>请确认您已收到商品，订单将标记为已完成。</p>
            <div class="modal-actions">
                <button id="confirm-receive-btn" class="btn-primary">确认收货</button>
                <button id="cancel-receive-btn" class="btn-secondary">返回</button>
            </div>
        </div>
    </div>

    <footer>
        <p>© 2025 电商平台</p>
    </footer>

    <script src="api.js"></script>
    <script>
        let currentCancelOrderId = null;
        let currentConfirmOrderId = null;
        let currentOrderPage = 1;
        const orderPageSize = 5;

        document.addEventListener('DOMContentLoaded', function() {
            // 检查登录状态
            checkLoginStatus();

            // 登录表单提交
            document.getElementById('login-form').addEventListener('submit', function(e) {
                e.preventDefault();
                loginUser();
            });

            // 注册表单提交
            document.getElementById('register-form').addEventListener('submit', function(e) {
                e.preventDefault();
                const username = document.getElementById('register-username').value;
                const password = document.getElementById('register-password').value;

                // 预留接口调用位置
                register(username, password).then(() => {
                    alert('注册成功，请登录');
                });
                // alert(`注册成功(模拟): ${username}`);
            });

            // 取消订单弹窗事件
            document.getElementById('confirm-cancel-btn').addEventListener('click', confirmCancelOrder);
            document.getElementById('cancel-cancel-btn').addEventListener('click', hideCancelModal);

            // 确认收货弹窗事件
            document.getElementById('confirm-receive-btn').addEventListener('click', confirmReceiveOrder);
            document.getElementById('cancel-receive-btn').addEventListener('click', hideConfirmModal);

            // 点击弹窗外部关闭
            document.getElementById('cancel-modal').addEventListener('click', function(e) {
                if (e.target === this) {
                    hideCancelModal();
                }
            });

            document.getElementById('confirm-modal').addEventListener('click', function(e) {
                if (e.target === this) {
                    hideConfirmModal();
                }
            });
        });

        function checkLoginStatus(isLoggedIn = false) {
            // 检查本地存储的登录状态
            const userToken = localStorage.getItem('userToken');
            const loggedIn = isLoggedIn || !!userToken;

            updateUI(loggedIn);
            if (loggedIn) {
                loadUserInfo();
                loadOrderHistory(currentOrderPage);
            }
        }

        function updateUI(loggedIn) {
            const loginSection = document.getElementById('login-section');
            const registerSection = document.getElementById('register-section');
            const userInfoSection = document.getElementById('user-info-section');
            const orderHistorySection = document.getElementById('order-history-section');

            if (loggedIn) {
                loginSection.style.display = 'none';
                registerSection.style.display = 'none';
                userInfoSection.style.display = 'block';
                orderHistorySection.style.display = 'block';
            } else {
                loginSection.style.display = 'block';
                registerSection.style.display = 'block';
                userInfoSection.style.display = 'none';
                orderHistorySection.style.display = 'none';
            }
        }

        function loadUserInfo() {
            getUserInfo().then(result => {
                if (result.data) {
                    renderUserInfo(result.data);
                } else {
                    throw new Error('获取用户信息失败');
                }
            }).catch(error => {
                console.error('获取用户信息失败:', error);
                handleApiError(error);
            });
        }

        function renderUserInfo(user) {
            console.log('用户数据:', user); // 调试信息
            
            const container = document.getElementById('user-info-section');
            
            // 安全处理余额数据
            const balance = user.money !== undefined && user.money !== null ? Number(user.money) : 0;
            // 格式化注册日期
            const joinDate = user.createTime ? new Date(user.createTime).toLocaleDateString() : '未知';
            
            container.innerHTML = `
                <div class="user-profile">
                    <h2>个人信息</h2>
                    <div class="user-details">
                        <p><strong>用户名:</strong> ${user.username || '未知'}</p>
                        <p><strong>昵称:</strong> ${user.nickname || user.username || '未设置'}</p>
                        <p><strong>账户余额:</strong> ¥${balance.toFixed(2)}</p>
                        <p><strong>注册日期:</strong> ${joinDate}</p>
                        <p><strong>账户状态:</strong> ${user.enableFlag ? '正常' : '已禁用'}</p>
                    </div>
                    <div class="user-actions">
                        <button onclick="recharge()" class="btn-primary">充值</button>
                        <button onclick="logoutUser()" class="btn-secondary">退出登录</button>
                    </div>
                </div>
            `;
        }

        function loadOrderHistory(page) {
            // 预留接口调用位置
            // getOrderHistory(page, orderPageSize).then(data => {
            //     renderOrderHistory(data.records);
            //     renderOrderPagination(data.current, data.size, data.total);
            // });

            // 从本地存储获取订单并分页
            const allOrders = JSON.parse(localStorage.getItem('userOrders') || '[]');
            const start = (page - 1) * orderPageSize;
            const end = start + orderPageSize;
            const paginatedOrders = allOrders.slice(start, end);

            renderOrderHistory(paginatedOrders);
            renderOrderPagination(page, orderPageSize, allOrders.length);
        }

        function renderOrderHistory(orders) {
            const container = document.getElementById('order-list');
            if (orders.length === 0) {
                container.innerHTML = '<div class="no-orders">暂无订单记录</div>';
                return;
            }

            container.innerHTML = orders.map(order => `
                <div class="order-item">
                    <div class="order-header">
                        <span class="order-id">订单号: ${order.id}</span>
                        <div class="order-status-actions">
                            <span class="order-status status-${getStatusClass(order.status)}">${order.status}</span>
                            <div class="order-buttons">
                                ${order.status === '已下单' ? `
                                    <button onclick="showConfirmModal(${order.id})" class="btn-confirm">确认收货</button>
                                    <button onclick="showCancelModal(${order.id})" class="btn-cancel">取消订单</button>
                                ` : ''}
                            </div>
                        </div>
                    </div>
                    <div class="order-details">
                        <p><strong>商品:</strong> ${order.productName}</p>
                        <p><strong>数量:</strong> ${order.quantity}</p>
                        <p><strong>单价:</strong> ¥${order.unitPrice.toFixed(2)}</p>
                        <p><strong>总价:</strong> ¥${order.totalPrice.toFixed(2)}</p>
                        <p><strong>下单时间:</strong> ${order.createTime}</p>
                        ${order.completeTime ? `<p><strong>完成时间:</strong> ${order.completeTime}</p>` : ''}
                        ${order.cancelTime ? `<p><strong>取消时间:</strong> ${order.cancelTime}</p>` : ''}
                    </div>
                </div>
            `).join('');
        }

        function renderOrderPagination(current, size, total) {
            const totalPages = Math.ceil(total / size);
            const pagination = document.getElementById('order-pagination');

            if (totalPages <= 1) {
                pagination.innerHTML = '';
                return;
            }

            let paginationHTML = '';

            // 上一页
            if (current > 1) {
                paginationHTML += `<button onclick="goToOrderPage(${current - 1})">上一页</button>`;
            }

            // 页码
            for (let i = 1; i <= totalPages; i++) {
                if (i === current) {
                    paginationHTML += `<button class="current">${i}</button>`;
                } else {
                    paginationHTML += `<button onclick="goToOrderPage(${i})">${i}</button>`;
                }
            }

            // 下一页
            if (current < totalPages) {
                paginationHTML += `<button onclick="goToOrderPage(${current + 1})">下一页</button>`;
            }

            pagination.innerHTML = paginationHTML;
        }

        function goToOrderPage(page) {
            currentOrderPage = page;
            loadOrderHistory(page);
        }

        function getStatusClass(status) {
            switch(status) {
                case '已下单': return 'pending';
                case '已取消': return 'cancelled';
                case '已完成': return 'completed';
                default: return 'pending';
            }
        }

        function showCancelModal(orderId) {
            currentCancelOrderId = orderId;
            document.getElementById('cancel-modal').style.display = 'flex';
        }

        function hideCancelModal() {
            currentCancelOrderId = null;
            document.getElementById('cancel-modal').style.display = 'none';
        }

        function showConfirmModal(orderId) {
            currentConfirmOrderId = orderId;
            document.getElementById('confirm-modal').style.display = 'flex';
        }

        function hideConfirmModal() {
            currentConfirmOrderId = null;
            document.getElementById('confirm-modal').style.display = 'none';
        }

        function confirmCancelOrder() {
            if (!currentCancelOrderId) return;

            // 预留接口调用位置
            // cancelOrder(currentCancelOrderId).then(result => {
            //     if (result.success) {
            //         alert('订单取消成功，金额已退回账户');
            //         loadOrderHistory(currentOrderPage);
            //         loadUserInfo();
            //     }
            // });

            // 模拟取消订单
            const orders = JSON.parse(localStorage.getItem('userOrders') || '[]');
            const orderIndex = orders.findIndex(order => order.id === currentCancelOrderId);

            if (orderIndex !== -1 && orders[orderIndex].status === '已下单') {
                // 更新订单状态
                orders[orderIndex].status = '已取消';
                orders[orderIndex].cancelTime = new Date().toLocaleString();

                // 退款到用户余额
                const currentBalance = parseFloat(localStorage.getItem('userBalance') || '0');
                const refundAmount = orders[orderIndex].totalPrice;
                const newBalance = currentBalance + refundAmount;
                localStorage.setItem('userBalance', newBalance.toString());

                // 保存更新后的订单
                localStorage.setItem('userOrders', JSON.stringify(orders));

                alert(`订单取消成功！\n退款金额: ¥${refundAmount.toFixed(2)}\n当前余额: ¥${newBalance.toFixed(2)}`);

                // 刷新页面数据
                loadOrderHistory(currentOrderPage);
                loadUserInfo();
            }

            hideCancelModal();
        }

        function confirmReceiveOrder() {
            if (!currentConfirmOrderId) return;

            // 预留接口调用位置
            // confirmReceiveOrder(currentConfirmOrderId).then(result => {
            //     if (result.success) {
            //         alert('确认收货成功，订单已完成');
            //         loadOrderHistory(currentOrderPage);
            //     }
            // });

            // 模拟确认收货
            const orders = JSON.parse(localStorage.getItem('userOrders') || '[]');
            const orderIndex = orders.findIndex(order => order.id === currentConfirmOrderId);

            if (orderIndex !== -1 && orders[orderIndex].status === '已下单') {
                // 更新订单状态
                orders[orderIndex].status = '已完成';
                orders[orderIndex].completeTime = new Date().toLocaleString();

                // 保存更新后的订单
                localStorage.setItem('userOrders', JSON.stringify(orders));

                alert('确认收货成功，订单已完成！');

                // 刷新页面数据
                loadOrderHistory(currentOrderPage);
            }

            hideConfirmModal();
        }

        function loginUser() {
            const username = document.getElementById('login-username').value;
            const password = document.getElementById('login-password').value;

            if (!username || !password) {
                alert('请输入用户名和密码');
                return;
            }

            // 调用真实登录API
            login(username, password).then(result => {
                if (result.code === 1 && result.data) {
                    alert('登录成功！');
                    checkLoginStatus(true);
                } else {
                    throw new Error(result.message || '登录失败');
                }
            }).catch(error => {
                console.error('登录失败:', error);
                alert(error.message || '登录失败，请检查用户名和密码');
            });
        }

        function recharge() {
            const amount = prompt('请输入充值金额:');
            if (amount && !isNaN(amount) && parseFloat(amount) > 0) {
                // TODO: 这里应该调用后端充值API
                // rechargeBalance(parseFloat(amount)).then(result => {
                //     if (result.success) {
                //         alert(`充值成功！充值金额: ¥${parseFloat(amount).toFixed(2)}`);
                //         loadUserInfo(); // 刷新用户信息
                //     }
                // }).catch(error => {
                //     alert('充值失败: ' + error.message);
                // });
                
                // 临时的本地模拟充值
                alert(`充值功能开发中\n充值金额: ¥${parseFloat(amount).toFixed(2)}`);
                console.log('充值金额:', parseFloat(amount));
            } else {
                alert('请输入有效的充值金额');
            }
        }

        function logoutUser() {
            // 调用后端退出登录API（api.js中的logout函数）
            logout().then(() => {
                localStorage.removeItem('username');
                alert('已退出登录');
                checkLoginStatus(false);
            }).catch(error => {
                console.error('退出登录API调用失败:', error);
                // 即使API调用失败，也清除本地token
                localStorage.removeItem('userToken');
                localStorage.removeItem('username');
                alert('已退出登录');
                checkLoginStatus(false);
            });
        }
    </script>
</body>
</html>